import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { passportActions, protoActions } from 'reduxs'
import Sider from './sider'
import Header from './header'
import * as menuSubs from 'features/menuSub'
import _ from 'lodash'
import { getSiderMenus, getPageFlag, getFlagValue } from 'services/utils'
import { PageNotFound, Layout } from 'components'
import { LoginScreen } from '../passport'
import Flags from '../config/flag'

@connect(
  state => ({
    auth: state.Passport.auth,
    rtsp_keys: state.Passport.rtsp_keys,
    rtsp_key: state.Passport.rtsp_key,
    protoDataPending: state.Proto.postDataPending
  }),
  dispatch => ({
    actions: bindActionCreators({
      ...passportActions,
      stopProtoData: protoActions.stopData
    }, dispatch)
  })
)
export default class CoreLayout extends PureComponent {
  
  static propTypes = {
    location: PropTypes.object,
    children: PropTypes.any,
    auth: PropTypes.object,
    pageCode: PropTypes.string,
    breadcrumb: PropTypes.array,
    errCode: PropTypes.number
  }
  
  static defaultProps = {
    location: null,
    children: null,
    auth: null,
    pageCode: undefined,
    breadcrumb: null,
    errCode: 0
  }

  render () {
    const { location, children, auth, rtsp_keys, rtsp_key, pageCode, breadcrumb, errCode, protoDataPending } = this.props
    let siderMenus = getSiderMenus(menuSubs, getMenuOptions(auth))
    const options = {
      auth,
      pageCode: auth.group.level === 9999 ? 'none' : pageCode,
      breadcrumb,
      permissionView: <PageNotFound code={403} />,
      sider: (
        <Sider {...{ location, menuSubs: siderMenus }} />
      ),
      header: (
        <Header {...{ auth, location, rtsp_keys, rtsp_key, actions: this.props.actions, protoDataPending }} />
      ),
      pageLoading: true
    }
    return errCode === 1001 ? <LoginScreen location={location}/> : (
      <Layout {...options}>
        {children}
      </Layout>
    )
  }
}

const getMenuOptions = (auth) => {
  let menuOptions = []
  for (let e of _.keys(menuSubs)) {
    let subTag = _.kebabCase(e.replace(/^(menuSub)/, ''))
    let subChildren = []
    let childrenData = menuSubs[e]['data']
    for (let item of childrenData) {
      let itemKey = item['key']
      let itemFlag = getPageFlag(`/${subTag}/${itemKey}`, 'access')
      subChildren.push({
        key: itemKey,
        open: !getFlagValue(auth, itemFlag.value, null)
      })
    }
    menuOptions.push({
      key: subTag,
      open: _.find(subChildren, o => o.open) || subTag === 'home' ? true : false,
      children: subChildren
    })
  }
  return menuOptions
}